package com.qd.extcamclientv2;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class LoginActivity extends Activity implements View.OnClickListener, IOnHandlerMessage {
	private static final String TAG = "ExtCamClientV2";
	private void _log(String log) {
		Log.i(TAG, "LoginActivity: " + log);
	}

	private static final int HANDLER_TIMER = 1;
	private static final long TIMER_INTERVAL = 2000;
	private static final String DEVICE_SSID = "\"Marvell Micro AP\"";

	private WifiManager mWifiManager = null;
	private int mNetworkId = -1;
	private WeakRefHandler mHandler = null;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		((TextView)findViewById(R.id.edt_hostaddr)).setText("192.168.100.1");
		findViewById(R.id.btn_login).setOnClickListener(this);
		findViewById(R.id.btn_exit).setOnClickListener(this);

		mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		if (false == mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}

		mHandler = new WeakRefHandler((IOnHandlerMessage)this);
		mHandler.sendEmptyMessageDelayed(HANDLER_TIMER, TIMER_INTERVAL);
	}

	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
		.setMessage(R.string.dlg_msg_exit).setCancelable(false)
		.setNegativeButton(R.string.dlg_btn_cancel, null)
		.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		})
		.show();

		//super.onBackPressed();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		mHandler.removeMessages(HANDLER_TIMER);

		if (true == mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}

		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View arg0) {
		int nId = arg0.getId();
		_log("onClick(" + nId + ")");

		switch (nId) {
		case R.id.btn_login:
			if (checkWifiState()) {
				mHandler.removeMessages(HANDLER_TIMER);

				Intent intent = new Intent(this, RecorderActivity.class);
				TextView tvw = (TextView)findViewById(R.id.edt_hostaddr);
				intent.putExtra(RecorderActivity.EXTRA_HOSTADDR, tvw.getText().toString());
				startActivityForResult(intent, 1);
			}
			break;
		case R.id.btn_exit:
			new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
			.setMessage(R.string.dlg_msg_exit).setCancelable(false)
			.setNegativeButton(R.string.dlg_btn_cancel, null)
			.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.show();
			break;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (1 == requestCode) {
			mHandler.sendEmptyMessageDelayed(HANDLER_TIMER, TIMER_INTERVAL);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/* (non-Javadoc)
	 * @see com.qd.extcamclientv2.IOnHandlerMessage#handleMessage(android.os.Message)
	 */
	@Override
	public void handleMessage(Message msg) {
		if (HANDLER_TIMER == msg.what) {
			if (checkWifiState()) {
				findViewById(R.id.btn_login).setEnabled(true);
			} else {
				findViewById(R.id.btn_login).setEnabled(false);
			}
		}

		mHandler.sendEmptyMessageDelayed(HANDLER_TIMER, TIMER_INTERVAL);
	}

	/**
	 * @return
	 */
	private boolean checkWifiState() {
		switch (mWifiManager.getWifiState()) {
		case WifiManager.WIFI_STATE_ENABLED:
			if (0 > mNetworkId) {
				List<WifiConfiguration> networks = mWifiManager.getConfiguredNetworks();
				for (int i=0; i<networks.size(); i++) {
					//_log("WifiConfiguration(" + i + ") = " + networks.get(i).SSID + ", " + networks.get(i).networkId + ")");
					if (DEVICE_SSID.equals(networks.get(i).SSID)) {
						mNetworkId = networks.get(i).networkId;
						mWifiManager.enableNetwork(mNetworkId, true);
						break;
					}
				}
			} else {
				WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
				_log("getNetworkId(" + wifiInfo.getNetworkId() + ")");
				if (mNetworkId != wifiInfo.getNetworkId()) {
					mWifiManager.enableNetwork(mNetworkId, true);
				} else {
					return true;
				}
			}
			break;
		case WifiManager.WIFI_STATE_DISABLED:
		case WifiManager.WIFI_STATE_DISABLING:
		case WifiManager.WIFI_STATE_ENABLING:
		case WifiManager.WIFI_STATE_UNKNOWN:
		default:
			_log("checkWifiState(" + mWifiManager.getWifiState() + ")");
			break;
		}

		return false;
	}
}
